package com.itheima.Service.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Service.CategoryService;
import com.itheima.Service.DishService;
import com.itheima.Service.SetmealService;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.Setmeal;
import com.itheima.common.PageParam;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.DishDao;
import com.itheima.dto.DishDto;
import com.itheima.exception.CustomException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CategorySerivceImpl implements CategoryService {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryDao categoryDao;


    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @Override
    public int add(Category category) {

        return categoryDao.insert(category);
    }

    /**
     * 分类_分页查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Category> findPage(PageParam pageParam) {

        IPage<Category> page = new Page<>(pageParam.getPage(),pageParam.getPageSize());

        //构建条件对象
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //设置条件
        lqw.orderBy(true,true,Category::getSort);
        //执行分页查询
        return categoryDao.selectPage(page,lqw);
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @Override
    public int delete(long id) {

        //查询是否和菜品有关联
        List<DishDto> dishList = dishService.findByCategoryId(id,1);

        //有关联的禁止删除
        if(dishList !=null && dishList.size() > 0){
            throw new CustomException("有关联的菜品数据，禁止删除");
        }

        //查询是否和套餐有关联
        List<Setmeal> setmealList = setmealService.findByCategoryId(id);

        //有关联的禁止删除
        if(setmealList != null && setmealList.size() > 0){
            throw new CustomException("有关联的套餐数据，禁止删除！");
        }

        //都没有，直接删除
        return categoryDao.deleteById(id);
    }

    /**
     * 更新分类
     *
     * @param category
     * @return
     */
    @Override
    public int update(Category category) {
        return categoryDao.updateById(category);
    }

    @Override
    public Category findById(long id) {
        return categoryDao.selectById(id);
    }
}
